package com.atguigu.scw.manager.controller.permission;

import com.atguigu.scw.manager.bean.TRole;
import com.atguigu.scw.manager.bean.TUser;
import com.atguigu.scw.manager.bean.TUserExample;
import com.atguigu.scw.manager.constant.Constans;
import com.atguigu.scw.manager.service.RoleService;
import com.atguigu.scw.manager.service.UserRoleService;
import com.atguigu.scw.manager.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RequestMapping("/permission/user")
@Controller
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 用户注册
     *
     * @param user
     * @param model
     * @param httpSession
     * @return
     */
    @PostMapping("/reg")
    public String reg(TUser user, Model model, HttpSession httpSession) {
        logger.info("用户注册user:{}", user);
        // 注册用户
        boolean flag = userService.register(user);
        if (flag) {
            // 用户保存的数据在user对象中，id是数据库生成的自增主键
            // 需要修改mybatis的mapper文件，让其使用自动生成的id
            httpSession.setAttribute(Constans.LOGIN_USER, user);
            // 公司用户注册成功后来到后台的控制面板
            return "redirect:/main.html";
        } else {
            // 注册失败
            model.addAttribute("regError", "用户名已经被使用");
            // 来到页面要回显user之前输入的内容
            // user先从隐含模型中拿的；只要是pojo，确定完值以后会自动的放在隐含模型中
            // 驮峰命名的key是类名首字母小写
            // 如果类名是两个大写挨着，key就是全类名 ${TUser.loginacct}
            return "forward:/reg.jsp";
        }
    }

    /**
     * 用户登录
     *
     * @param user
     * @param httpSession 重定向，将用户信息放到session中
     * @return
     */
    @PostMapping("/login")
    public String login(TUser user, HttpSession httpSession) {
        logger.debug("注册用户信息：{}", user);
        TUser login = userService.login(user);
        if (null == login) {
            // 登录失败
            logger.debug("登录失败:{}", user);
            // 设置回显
            httpSession.setAttribute("errorUser", user);
            httpSession.setAttribute("msg", "登录失败");
            return "redirect:/login.jsp";
        }
        // 登录成功
        logger.debug("登录成功！");
        // 将用户放到session域中
        httpSession.setAttribute(Constans.LOGIN_USER, login);
        // 避免表单重复提交，使用重定向
        return "redirect:/main.html";
    }

    @RequestMapping("/list")
    public String userList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize,
                           Model model,
                           @RequestParam(value = "searchParam", defaultValue = "") String searchParam) {
        logger.debug("分页显示用户维护列表:pageNum={},pageSize={},searchParam={}", pageNum, pageSize, searchParam);
        PageHelper.startPage(pageNum, pageSize);
        // 分页查出的结果
        //List<TUser> userList = userService.getAll();
        TUserExample example = new TUserExample();
        if (!"".equals(searchParam.trim())) {
            // 第一次创建的条件默认是使用and连接的
            TUserExample.Criteria criteria1 = example.createCriteria();
            TUserExample.Criteria criteria2 = example.createCriteria();
            TUserExample.Criteria criteria3 = example.createCriteria();
            criteria1.andLoginacctLike("%" + searchParam.trim() + "%");
            criteria2.andUsernameLike("%" + searchParam + "%");
            criteria3.andEmailLike("%" + searchParam + "%");
            example.or(criteria2);
            example.or(criteria3);
        }
        List<TUser> userList = userService.getAllByExample(example);
        // 去页面显示的数据
        PageInfo<TUser> userPageInfo = new PageInfo<>(userList, 5);
        model.addAttribute(Constans.USER_PAGE, userPageInfo);
        model.addAttribute("searchParam", searchParam);
        // 有表单提交的，为了防止重复提交，建议通过额外写一个转发方法重定向到页面，没有表单提交的，就直接转发到目标页面
        return "manager/permission/user";
    }

    /**
     * 删除多个用户或者单个用户
     *
     * @param ids 用户id，多个用户用逗号分割
     * @return 列表页面
     */
    @RequestMapping("/del")
    public String userDelete(@RequestParam(value = "ids", defaultValue = "") String ids,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        logger.debug("删除单个或者多个用户:ids={}, pageNum={}", ids, pageNum);
        if (!"".equals(ids.trim())) {
            userService.deleteBatchOrSingle(ids);
        }
        return "redirect:/permission/user/list?pageNum=" + pageNum;
    }

    /**
     * 去权限分配页面
     *
     * @param userId
     * @return
     */
    @RequestMapping("/listUserRoles")
    public String listUserRoles(@RequestParam(value = "userId", defaultValue = "") Integer userId,
                                Model model) {
        logger.debug("去用户权限页面，userId:{}", userId);
        //查出所有角色
        List<TRole> allRoles = roleService.getAllRole();
        // 查出当前用户已经获得的角色
        HashMap<Integer, TRole> userRolesMap = new HashMap<>();
        List<TRole> userRoles = roleService.getUserRole(userId);
        for (TRole userRole : userRoles) {
            userRolesMap.put(userRole.getId(), userRole);
        }
        // 用户未分配的权限
        List<TRole> unRoles = new ArrayList<>();
        for (TRole allRole : allRoles) {
            if (!userRolesMap.containsKey(allRole.getId())) {
                unRoles.add(allRole);
            }
        }
        model.addAttribute("unRoles", unRoles);
        model.addAttribute("userRoles", userRoles);
        return "manager/permission/assignRole";
    }

    /**
     * 如果返回返回值为空，默认请求地址就会被当成页面地址
     *
     * @param userId
     * @param roleIds
     */
    @ResponseBody
    @RequestMapping("/assignRoles")
    public String assignRoles(@RequestParam("userId") Integer userId,
                              @RequestParam(value = "roleIds", defaultValue = "") String roleIds,
                              @RequestParam("opt") String opt) {
        logger.debug("opt:{},userId:{}, rolesIds:{} ", opt, userId, roleIds);
        if ("add".equals(opt)) {
            if (!"".equals(roleIds.trim())) {
                // 为用户添加一些角色
                userRoleService.addRole(userId, roleIds);
                logger.debug("添加完成！");
            }
        } else if ("remove".equals(opt)) {
            if (!"".equals(roleIds.trim())) {
                // 删除角色
                userRoleService.removeRole(userId, roleIds);
                logger.debug("删除成功!");
            }
        } else {
            return "error";
        }
        return "ok";
    }

    @RequestMapping("/addUser")
    public String addUser(TUser user) {
        logger.debug("添加的用户： {}", user);
        userService.savaUser(user);
        // 开启PageHelper的分页的合理化参数，通过传入最大的pageNum后，使添加完成后，用户列表显示为最后一页
        return "redirect:/permission/user/list?pageNum=" + Integer.MAX_VALUE;
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam("userId") Integer userId, Model model) {
        logger.debug("userId:{}", userId);
        TUser user = userService.getUserById(userId);
        model.addAttribute("userInfo", user);
        return "manager/permission/edit";
    }

    @RequestMapping("/updateUser")
    public String updateUser(TUser user, Integer pageNum) {
        logger.debug("修改用户信息：{}, pageNum={}", user, pageNum);
        userService.updateUser(user);
        return "redirect:/permission/user/list?pageNum=" + pageNum;
    }
}
